package com.app.android.coliy.ui.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognitionService;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.android.coliy.R;
import com.app.android.coliy.adapter.FileEdit_ActionAdapter;
import com.app.android.coliy.adapter.FileEdit_AddElementsAdapter;
import com.app.android.coliy.bean.ActionInfo;
import com.app.android.coliy.bean.ElementsInfo;
import com.app.android.coliy.bean.ImgResultBean;
import com.app.android.coliy.bean.LocalFileInfo;
import com.app.android.coliy.bean.UploadFileInfo;
import com.app.android.coliy.dialog.CommList_Dialog;
import com.app.android.coliy.dialog.Comm_Dialog;
import com.app.android.coliy.dialog.Voice_Dialog;
import com.app.android.coliy.event.Event_ActionChange;
import com.app.android.coliy.event.Event_CurrentFile;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.manager.ActionManager;
import com.app.android.coliy.manager.ElementManager;
import com.app.android.coliy.service.RecognizeService;
import com.app.android.coliy.tool.CommLoading;
import com.app.android.coliy.tool.CommToast;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.ui.fragment.BlueToothListFragment;
import com.app.android.coliy.ui.view.DragViewContainer;
import com.app.android.coliy.ui.view.ElementView_Base;
import com.app.android.coliy.ui.view.View_MoveView;
import com.app.android.coliy.ui.view.View_PropertyView;
import com.app.android.coliy.util.BitmapUtil;
import com.app.android.coliy.util.ImageUtil;
import com.app.android.coliy.util.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;

import com.app.android.coliy.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static android.content.pm.PackageManager.MATCH_ALL;

/**
 * Created by Administrator on 2018/6/20.
 */

public class FileEditActivity extends BaseActivity {
    private TextView mTransferFileTextView;
    int RequestCode_Scan = 100;
    int RequestCode_SelectImgResult = 101;
    int RequestCode_Voice = 102;
    private boolean isEdited;

    public boolean isScreenOrientationPortrait() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            Log.d("有缓存数据");
        } else {
            Log.d("没有缓存数据");
        }

        String fileName = getIntent().getStringExtra("fileName");
        if (!TextUtils.isEmpty(fileName)) {
            List<LocalFileInfo> localFileList = DataSupport.findAll(LocalFileInfo.class);
            if (localFileList != null) {
                for (int i = 0; i < localFileList.size(); i++) {
                    if (fileName.equals(localFileList.get(i).filename)) {
                        localFileInfo = localFileList.get(i);
                        break;
                    }
                }
            }
        }
        if (localFileInfo == null) {
            localFileInfo = new LocalFileInfo();
            localFileInfo.filename = fileName;

            LocalFileInfo lastFileinfo = DataSupport.findLast(LocalFileInfo.class);
            if (lastFileinfo != null) {
                localFileInfo.sort = lastFileinfo.sort + 1;
            }
        }

        setContentView(R.layout.activity_fileedit);
        initView();
        getData();

    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        save(false);
    }

    LocalFileInfo localFileInfo;

    RecyclerView recyclerview, recyclerview_action;
    DragViewContainer dragviewcontainer;
    View_MoveView view_move;
    View_PropertyView view_propertyview;
    SeekBar seekbar;
    HorizontalScrollView horizontalscrollview;

    FileEdit_AddElementsAdapter elementsAdapter;
    FileEdit_ActionAdapter actionAdapter;

    //初始化控件
    private void initView() {
        setTitle(localFileInfo.filename);    //设置标题
        setLeftImgClickListener();  //设置左键返回
        setRightImgClickListener(R.drawable.ico_save_white);
//        setRightImg1ClickListener(R.drawable.ico_colorpicker);

        mTransferFileTextView = findViewById(R.id.tv_transfer_file);

        recyclerview = findViewById(R.id.recyclerview);
        GridLayoutManager gm = new GridLayoutManager(mContext, 4);
        if (isScreenOrientationPortrait()) {
            recyclerview.setLayoutManager(gm);
        } else {
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(RecyclerView.HORIZONTAL);
            recyclerview.setLayoutManager(layoutManager);
        }
        elementsAdapter = new FileEdit_AddElementsAdapter(mContext, onElementClick);
        recyclerview.setAdapter(elementsAdapter);
//        refreshRecyclerviewLayoutManager();

        recyclerview_action = findViewById(R.id.recyclerview_action);
        LinearLayoutManager lm = new LinearLayoutManager(mContext);
        lm.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview_action.setLayoutManager(lm);
        actionAdapter = new FileEdit_ActionAdapter(mContext, onActionClick);
        recyclerview_action.setAdapter(actionAdapter);
        actionAdapter.setData(ActionManager.getAllAction());


        dragviewcontainer = findViewById(R.id.dragviewcontainer);
        dragviewcontainer.setCallBack_Edit(onElementSelect);
        view_move = findViewById(R.id.view_move);
        view_move.setCallBack(onMove);

        view_propertyview = findViewById(R.id.view_propertyview);
        seekbar = findViewById(R.id.seekbar);
        horizontalscrollview = findViewById(R.id.horizontalscrollview);

        //初始化元素
        try {
            localFileInfo.views = new Gson().fromJson(localFileInfo.viewStr, new TypeToken<List<ElementsInfo>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (localFileInfo.views != null) {
            Log.i("localFileInfo.views:" + localFileInfo.views.size());
            for (int i = 0; i < localFileInfo.views.size(); i++) {
                ElementView_Base view = ElementManager.getElementView(mContext, localFileInfo.views.get(i));
                dragviewcontainer.addDragView(view);
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            horizontalscrollview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View view, int x, int i1, int i2, int i3) {
                    float all = dragviewcontainer.getWidth() - horizontalscrollview.getWidth();
                    int progress = (int) (x / all * 1000f);
                    seekbar.setProgress(progress);
                }
            });
        }

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    float all = dragviewcontainer.getWidth() - horizontalscrollview.getWidth();
                    int x = (int) (all * (progress / 1000f));
                    horizontalscrollview.smoothScrollTo(x, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        mTransferFileTextView.setOnClickListener(v -> {
            //打印，传输文件
            //先保存，然后返回首页打印
            save(false);
            Event_CurrentFile eventCurrentFile = new Event_CurrentFile();
            eventCurrentFile.fileName = localFileInfo.filename;
            EventBus.getDefault().post(eventCurrentFile);
            finish();
        });
    }

    //网路请求 获取数据
    private void getData() {
        elementsAdapter.setData(ElementManager.getElementList());

    }

    //选中元素
    CommCallBack onElementSelect = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            if (view_propertyview.getVisibility() == View.VISIBLE) {
                if (dragviewcontainer.currentView != null) {
                    view_propertyview.setElementsInfo(dragviewcontainer.currentView);
                } else {
                    view_propertyview.close();
                }
            }
            if (view_move.getVisibility() == View.VISIBLE) {
                if (dragviewcontainer.currentView != null) {

                } else {
                    view_move.close();
                }
            }
        }
    };

    //元素点击
    CommCallBack onElementClick = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            final ElementsInfo info = (ElementsInfo) obj;
            addView(info);
        }
    };

    //操作事件回调
    CommCallBack onActionClick = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            ActionInfo actionInfo = (ActionInfo) obj;
            if (actionInfo.name == R.string.edit_action_print) {
                //先保存，然后返回首页打印
                save(false);

                if (!BlueToothListFragment.isConnected) {
                    ToastUtil.showWarning(mContext, getString(R.string.bluetooth_connect_tips));
                } else {
                    Event_CurrentFile eventCurrentFile = new Event_CurrentFile();
                    eventCurrentFile.fileName = localFileInfo.filename;
                    EventBus.getDefault().post(eventCurrentFile);
                    finish();
                }
            } else {
                isEdited = true;
                //删除
                if (R.string.edit_action_delete == actionInfo.name) {
                    dragviewcontainer.deleteCurrentView();
                    return;
                }
                if (dragviewcontainer.currentView != null) {
                    switch (actionInfo.name) {
//                        case R.string.edit_action_delete:
//                            dragviewcontainer.deleteCurrentView();
//                            break;
                        case R.string.edit_action_rotate:
                            dragviewcontainer.rotate();
                            break;
                        case R.string.edit_action_move:
                            view_move.show();
                            if (view_propertyview.getVisibility() == View.VISIBLE) {
                                view_propertyview.close();
                            }
                            break;
                        case R.string.edit_action_color:
                            //上色
                            if (dragviewcontainer.currentView == null) {
                                CommToast.showToast(mContext, Util.getString(R.string.edit_btn_select_ele));
                            } else {

                                isEdited = true;

                                if (view_propertyview.getVisibility() == View.GONE) {
                                    view_propertyview.setElementsInfo(dragviewcontainer.currentView);
                                    view_propertyview.show();
                                }
                                if (view_move.getVisibility() == View.VISIBLE) {
                                    view_move.close();
                                }
                                view_propertyview.showSelectColor();
                            }
                            break;
                        case R.string.edit_action_property:
                            view_propertyview.setElementsInfo(dragviewcontainer.currentView);
                            view_propertyview.show();
                            if (view_move.getVisibility() == View.VISIBLE) {
                                view_move.close();
                            }
                            break;
                        case R.string.edit_action_zoomout:
                            dragviewcontainer.sacle_small();
                            break;
                        case R.string.edit_action_zoomin:
                            dragviewcontainer.sacle_big();
                            break;
                        case R.string.edit_action_copy:
                            String str = new Gson().toJson(dragviewcontainer.currentView.elementView_base.elementsInfo);
                            ElementsInfo infotemp = new Gson().fromJson(str, ElementsInfo.class);
                            infotemp.xpos += 10;
                            infotemp.ypos += 10;
                            ElementView_Base view = ElementManager.getElementView(mContext, infotemp);
                            dragviewcontainer.addDragView(view);
                            break;
                    }
                } else {
                    CommToast.showToast(mContext, Util.getString(R.string.edit_btn_select_ele));
                }
            }
        }
    };

    //移动回调
    CommCallBack onMove = new CommCallBack() {
        @Override
        public void onResult(Object obj) {

            isEdited = true;

            dragviewcontainer.move((int) obj, horizontalscrollview.getScrollX());
        }
    };

    //添加元素
    private void addView(ElementsInfo infotemp) {

        isEdited = true;

        final ElementsInfo info = ElementManager.getElementInfo(infotemp.viewtype);
        //计算新元素x轴位置
        int maxX = 0;
        for (int i = 0; i < dragviewcontainer.mMoveLayoutList.size(); i++) {
            int right = dragviewcontainer.mMoveLayoutList.get(i).getRight();
            if (right > maxX) {
                maxX = right;
            }
        }
//        info.xpos = horizontalscrollview.getScrollX();
        info.xpos = maxX;

        if (!TextUtils.isEmpty(infotemp.text)) {
            info.text = infotemp.text;
        }
        //序列号+1
        if ("序列号".equals(info.viewtype)) {
            localFileInfo.serialNumber++;
            info.text = Util.getSerialNumber(localFileInfo.serialNumber);
        }

        //1:文本  2：条码  3：二维码  4：图片  5：Logo   6：线条  7 形状   8:序列号   9：时间  10 扫码  11 语音识别  12 图像识别
        switch (info.viewtype) {
            case "图片":
                //图片
                upLoadPhoto(false, new CommCallBack() {
                    @Override
                    public void onResult(Object obj) {
                        final UploadFileInfo fileInfo = (UploadFileInfo) obj;
                        CommLoading.showLoading(mContext);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                info.imgLocalPath = fileInfo.file.getAbsolutePath();
//                                Bitmap bitmap = BitmapUtil.compressQuality(fileInfo.bitmap, 10);
//                                info.base64 = ImageDispose.bitmapToString(bitmap);

                                Log.i("info.imgLocalPath:" + info.imgLocalPath);

                                int height = info.height;

                                int width = height;
                                if (fileInfo.height > 0) {

                                    double ratio = (double) fileInfo.width / fileInfo.height;
                                    int temp = (int) (ratio * info.height);
                                    if (temp > 0) {
                                        width = temp;
                                    }
                                }


                                info.width = width;


                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ElementView_Base view = ElementManager.getElementView(mContext, info);
                                        dragviewcontainer.addDragView(view);
                                        CommLoading.dismissLoading();
                                    }
                                });
                            }
                        }).start();
                    }
                });
                break;
            case "扫码":
                //扫码
                checkCameraPermission();
                break;
            case "语音识别":
                //语音识别
                startVoice();
//                startVoiceRecognitionActivity();
                break;
            case "图像识别":
                //图像识别
                upLoadPhoto(true, 2, 1, new CommCallBack() {
                    @Override
                    public void onResult(Object obj) {
                        UploadFileInfo fileInfo = (UploadFileInfo) obj;
                        ImageRecognition(fileInfo.file);
                    }
                });
                break;
            case "Logo":
                //Logo
//                Intent intent = new Intent(mContext, LogoListActivity.class);
//                startActivityForResult(intent, RequestCode_Logo);
                break;
            default:
                //其他默认
                ElementView_Base view = ElementManager.getElementView(mContext, info);
                dragviewcontainer.addDragView(view);
                horizontalscrollview.smoothScrollTo(maxX - horizontalscrollview.getWidth() + view.elementsInfo.width, 0);
                break;
        }
    }

    //保存
    public void save(boolean alertSaveSuccess) {

        try {
            dragviewcontainer.clearCurrent();

            localFileInfo.timestamp = System.currentTimeMillis() + "";
            localFileInfo.views = new ArrayList<>();

            int maxX = 0;
            for (int i = 0; i < dragviewcontainer.mMoveLayoutList.size(); i++) {
                localFileInfo.views.add(dragviewcontainer.mMoveLayoutList.get(i).elementView_base.elementsInfo);
                int right = dragviewcontainer.mMoveLayoutList.get(i).getRight();
                if (right > maxX) {
                    maxX = right;
                }
            }

            //生成截图
            Bitmap bitmap = ImageUtil.loadBitmapFromViewBySystem(dragviewcontainer);

            if (bitmap != null) {
                //裁剪掉多余的空白
                int width = maxX - 30;
                if (width <= 0) {
                    width = 1;
                }
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, bitmap.getHeight());
                //生成图片
//            bitmap = BitmapUtil.compressQuality(bitmap, 100);
                String filename = "snapshot_" + System.currentTimeMillis() + ".png";
                File tempFile = BitmapUtil.saveBitmapFile(bitmap, filename);

                localFileInfo.snapshot = tempFile.getAbsolutePath();

                Log.i("localFileInfo.snapshot:" + localFileInfo.snapshot);
                localFileInfo.viewStr = new Gson().toJson(localFileInfo.views);
                localFileInfo.save();

                isEdited = false;

                if (alertSaveSuccess) {
                    ToastUtil.showSuccess(mContext, getString(R.string.edit_btn_save));
                }
            } else {
                Log.d("BITMAP NULL");
            }

        } catch (Exception e) {

            ToastUtil.showError(mContext, e.getMessage());
        }
    }

    //点击事件
    @Override
    public void onClick(View view) {
        super.onClick(view);

        switch (view.getId()) {
            case R.id.public_title_right_img:
                save(true);
                break;
            case R.id.public_title_right_img1:   //颜色选择
                if (dragviewcontainer.currentView == null) {
                    CommToast.showToast(mContext, Util.getString(R.string.edit_btn_select_ele));
                } else {

                    isEdited = true;

                    if (view_propertyview.getVisibility() == View.GONE) {
                        view_propertyview.setElementsInfo(dragviewcontainer.currentView);
                        view_propertyview.show();
                    }
                    if (view_move.getVisibility() == View.VISIBLE) {
                        view_move.close();
                    }
                    view_propertyview.showSelectColor();
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {

        if (isEdited) {
            Comm_Dialog.showCommDialog(mContext, getString(R.string.comm_title_alert), getString(R.string.edit_exit_tips), getString(R.string.back_with_save), getString(R.string.back_with_no_save), new CommCallBack() {
                @Override
                public void onResult(Object obj) {
                    save(true);
                    finish();
                }
            }, new CommCallBack() {
                @Override
                public void onResult(Object obj) {
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    /**
     * 图片识别模块
     */
    private void ImageRecognition(File file) {
        CommLoading.showLoading(mContext, Util.getString(R.string.edit_img_reading));
        RecognizeService.recGeneralBasic(this, file.getAbsolutePath(), new RecognizeService.ServiceListener() {
            @Override
            public void onResult(String result) {
                CommLoading.dismissLoading();
                Log.i("result：" + result);
                //解析文字内容
                try {
                    ImgResultBean imgResultBean = new Gson().fromJson(result, ImgResultBean.class);
                    if (imgResultBean.words_result.size() == 1) {
                        showTextSelect(imgResultBean.words_result.get(0).words);
                    } else {
                        Intent intent = new Intent(mContext, ImgResultListActivity.class);
                        intent.putExtra("imgResultBean", imgResultBean);
                        startActivityForResult(intent, RequestCode_SelectImgResult);
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    /**
     * 语音识别模块
     */
    private void startVoice() {
        Voice_Dialog dialog = new Voice_Dialog(mContext);
        dialog.setIntputCallBack(new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                String result = (String) obj;
                showTextSelect(result);
            }
        });
        dialog.show();
    }

    private void startVoiceRecognitionActivity() {
//        //通过Intent传递语音识别的模式
//        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//        //语言模式和自由形式的语音识别
//        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//        //提示语音开始
//        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
//        //开始执行我们的Intent、语音识别
//        startActivityForResult(intent, RequestCode_Voice);

        if (checkVoice()) {
            // 开始语音识别 结果在 mSpeechRecognizer.setRecognitionListener(this);回调中
            mSpeechRecognizer.startListening(mRecognitionIntent);
        }
    }

    SpeechRecognizer mSpeechRecognizer;
    Intent mRecognitionIntent;

    private boolean checkVoice() {
        // 查找当前系统的内置使用的语音识别服务
        // com.huawei.vassistant/com.huawei.ziri.service.FakeRecognitionService
        String serviceComponent = Settings.Secure.getString(getContentResolver(),
                "voice_recognition_service");
        if (TextUtils.isEmpty(serviceComponent)) {
            return false;
        }
        ComponentName component = ComponentName.unflattenFromString(serviceComponent);
        if (component == null) {
            return false;
        }
        boolean isRecognizerServiceValid = false;
        ComponentName currentRecognitionCmp = null;

        // 查找得到的 "可用的" 语音识别服务
        List<ResolveInfo> list = getPackageManager().queryIntentServices(new Intent(RecognitionService.SERVICE_INTERFACE), MATCH_ALL);
        if (list != null && list.size() != 0) {
            for (ResolveInfo info : list) {
                if (info.serviceInfo.packageName.equals(component.getPackageName())) {
                    isRecognizerServiceValid = true;
                    break;
                } else {
                    currentRecognitionCmp = new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
                }

            }
        } else {
            return false;
        }

        if (mSpeechRecognizer != null) {
            return true;
        }

        if (isRecognizerServiceValid) {
            mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(mContext);
        } else {
            mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(mContext, currentRecognitionCmp);
        }

        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {
                Log.i("onReadyForSpeech");
            }

            @Override
            public void onBeginningOfSpeech() {
                Log.i("onBeginningOfSpeech");
            }

            @Override
            public void onRmsChanged(float v) {
                Log.i("onRmsChanged");
            }

            @Override
            public void onBufferReceived(byte[] bytes) {
                Log.i("onBufferReceived");
            }

            @Override
            public void onEndOfSpeech() {
                Log.i("onEndOfSpeech");
            }

            @Override
            public void onError(int i) {
                Log.i("onError:" + i);
            }

            @Override
            public void onResults(Bundle bundle) {
                Log.i("onResults");
            }

            @Override
            public void onPartialResults(Bundle bundle) {
                Log.i("onPartialResults");
            }

            @Override
            public void onEvent(int i, Bundle bundle) {
                Log.i("onEvent");
            }
        });

        if (mRecognitionIntent == null) {
            mRecognitionIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
        }
        return true;
    }

    /**
     * 扫码识别模块
     */

    int REQUEST_PERMISSION_CAMERA = 10001;

    //检查拍照权限
    private void checkCameraPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
            return;
        }
        openScan();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openScan();
            } else {
                CommToast.showToast(getApplicationContext(), "权限被禁止，无法打开相机");
            }
        }
    }

    private void openScan() {
        Intent intent = new Intent(mContext, ScanCaptureActivity.class);
        startActivityForResult(intent, RequestCode_Scan);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == RequestCode_Scan) {
                //扫码返回
                String result = data.getStringExtra("text");
                showTextSelect(result);
            } else if (requestCode == RequestCode_SelectImgResult) {
                //选择文本返回
                String result = data.getStringExtra("result");
                showTextSelect(result);
            } else if (requestCode == RequestCode_Voice) {
                // 取得语音的字符
                ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                if (results != null && results.size() > 0) {
                    showTextSelect(results.get(0));
                }
            }
        }
    }

    //选择文本插入类型
    private void showTextSelect(final String result) {
        List<String> list = new ArrayList<>();
        list.add(Util.getString(R.string.edit_create_as_text));
        list.add(Util.getString(R.string.edit_create_as_tiaoma));
        list.add(Util.getString(R.string.edit_create_as_erweima));
        CommList_Dialog dialog = new CommList_Dialog(mContext);
        dialog.setData(list, result, true, true);
        dialog.setCallBack(new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                int str = (int) obj;
                ElementsInfo info = null;
                //1:文本  2：条码  3：二维码  4：图片  5：Logo   6：线条  7 形状   8:序列号   9：时间  10 扫码  11 语音识别  12 图像识别
                switch (str) {
                    case 0:
                        info = ElementManager.getElementInfo("文本");
                        break;
                    case 1:
                        info = ElementManager.getElementInfo("条码");
                        break;
                    case 2:
                        info = ElementManager.getElementInfo("二维码");
                        break;
                }
                info.text = result;
                addView(info);
            }
        });
        dialog.show();
    }

    //收到刷新控件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_ActionChange event) {
        view_propertyview.bindUI();

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.i("横屏");
            if (recyclerview != null) {
                LinearLayoutManager lm = new LinearLayoutManager(mContext);
                lm.setOrientation(RecyclerView.HORIZONTAL);
                recyclerview.setLayoutManager(lm);
                elementsAdapter.setOrientation(true);

                //全屏
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                getWindow().setAttributes(lp);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
//                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.i("竖屏");
            if (recyclerview != null) {
                GridLayoutManager gm = new GridLayoutManager(mContext, 4);
                recyclerview.setLayoutManager(gm);
                elementsAdapter.setOrientation(false);
                //不全屏
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setAttributes(lp);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        }
    }

    private void refreshRecyclerviewLayoutManager() {
        if (recyclerview != null && elementsAdapter != null) {
            if (getChangingConfigurations() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                //横屏
                LinearLayoutManager lm = new LinearLayoutManager(mContext);
                lm.setOrientation(RecyclerView.HORIZONTAL);
                recyclerview.setLayoutManager(lm);
                elementsAdapter.setOrientation(true);

                //全屏
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                getWindow().setAttributes(lp);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            } else {
                //竖屏
                GridLayoutManager gm = new GridLayoutManager(mContext, 4);
                recyclerview.setLayoutManager(gm);
                elementsAdapter.setOrientation(false);
                //不全屏
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setAttributes(lp);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        }
    }
}
